package com.white.databasesbackup;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * <p>
 * Insert语句封装
 * </p>
 *
 * @author huangzy
 * @since 2022/5/6
 */
public class InsertSql {

    /**
     * 数据库名称
     */
    private final String databasesName;

    /**
     * 表名称
     */
    private final String tableName;

    /**
     * 实体类
     */
    private final Map<String,Object> entity;

    private static final String CALLOUT = "`%s`";
    private static final String APOSTROPHE = "'%s'";

    public InsertSql(String databasesName, String tableName, Map<String, Object> entity) {
        this.databasesName = databasesName;
        this.tableName = tableName;
        this.entity = entity;
    }

    /**
     * 获取SQL
     */
    public String toSql(){
        StringBuilder sql = new StringBuilder("INSERT INTO ");
        sql.append(String.format(CALLOUT, databasesName));
        sql.append(".");
        sql.append(String.format(CALLOUT, tableName));
        sql.append(" (");
        for (Map.Entry<String, Object> entry : entity.entrySet()) {
            sql.append(String.format(CALLOUT,entry.getKey()));
            sql.append(",");
        }
        sql.replace(sql.length()-1,sql.length(),"");
        sql.append(") ");
        sql.append("VALUES (");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (Map.Entry<String, Object> entry : entity.entrySet()) {
            if (entry.getValue() != null && entry.getValue() instanceof LocalDateTime) {
                sql.append(String.format(APOSTROPHE,((LocalDateTime) entry.getValue()).format(formatter)));
            } else if (entry.getValue() instanceof Boolean) {
                sql.append(entry.getValue());
            } else if (entry.getValue() != null) {
                sql.append(String.format(APOSTROPHE,entry.getValue()));
            } else {
                sql.append("NULL");
            }
            sql.append(",");
        }
        sql.replace(sql.length()-1,sql.length(),"");
        sql.append(");");
        return sql.toString();
    }
}
